package kmp;

import java.util.Arrays;

/**
 * @description: kmp算法
 * @author: wangjun
 * @create: 2022-05-06
 */
public class KmpMain {

    public static void main(String[] args) {

        String str1 = "AABSADFDFV";
        String str2 = "FV";


        int[] next = next("ABCDABD");
        System.out.println(Arrays.toString(next));

        System.out.println(kmpSearch(str1, str2, next));
    }

    /**
     * 根据部分匹配表进行字符串匹配
     *
     * @param str1 源串
     * @param str2 子串
     * @param next str2子串的部分匹配表值
     * @return int
     */
    public static int kmpSearch(String str1, String str2, int[] next) {
        for (int i = 0, j = 0; i < str1.length(); i++) {
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    /**
     * 计算待匹配字符串的部分匹配表
     *
     * @param dest 目标串
     * @return int[]
     */
    public static int[] next(String dest) {
        //AAAB 前缀 A AA AAA  后缀 A AA AAB next = [0,1,2,0]
        int[] next = new int[dest.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < dest.length(); i++) {
            //如果两个位置的字符不相等时，则将j 后退
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            // 如果两个位置的字符相等时，则使j++
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

}